package com.ruoyi.repair.repairApprove.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.ruoyi.activiti.service.IProcessService;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.repair.repairApprove.domain.BizVehicleRepairVo;
import com.ruoyi.api.activiti.domain.ExpenseReport;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.util.HttpClientUtil;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.TaskEntityImpl;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.ruoyi.repair.repairApprove.mapper.BizVehicleRepairMapper;
import com.ruoyi.repair.repairApprove.domain.BizVehicleRepair;
import com.ruoyi.repair.repairApprove.service.IBizVehicleRepairService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.util.CollectionUtils;

/**
 * 维修申请Service业务层处理
 *
 * @author xzshan
 * @date 2020-06-03
 */
@Service
public class BizVehicleRepairServiceImpl implements IBizVehicleRepairService {
  @Autowired
  private BizVehicleRepairMapper bizVehicleRepairMapper;
  @Autowired
  private RuntimeService runtimeService;
  @Autowired
  private TaskService taskService;
  @Autowired
  private HistoryService historyService;
  @Autowired
  private SysUserMapper userMapper;
  @Autowired
  private IProcessService processService;

  @Value("${wspaas.dailyworkUrl}")
  private String dwUrl;
  /**
   * 查询维修申请
   *
   * @param id 维修申请ID
   * @return 维修申请
   */
  @Override
  public BizVehicleRepairVo selectBizVehicleRepairById(Long id) {
    BizVehicleRepairVo bizVehicleRepairvo = bizVehicleRepairMapper.selectBizVehicleRepairById(id);
    SysUser sysUser = userMapper.selectUserByLoginName(bizVehicleRepairvo.getApplyUser());
    if (sysUser != null) {
      bizVehicleRepairvo.setApplyUserName(sysUser.getUserName());
    }
    return bizVehicleRepairvo;
  }

  /**
   * 查询维修申请列表
   *
   * @param bizVehicleRepair 维修申请
   * @return 维修申请
   */
  @Override
  public List<BizVehicleRepairVo> selectBizVehicleRepairList(BizVehicleRepairVo bizVehicleRepair) {
    PageDomain pageDomain = TableSupport.buildPageRequest();
    Integer pageNum = pageDomain.getPageNum();
    Integer pageSize = pageDomain.getPageSize();

    // PageHelper 仅对第一个 List 分页
    Page<BizVehicleRepairVo> list = (Page<BizVehicleRepairVo>) bizVehicleRepairMapper.selectBizVehicleRepairList(bizVehicleRepair);
    Page<BizVehicleRepairVo> returnList = new Page<>();
    for (BizVehicleRepairVo vehicleRepair : list) {
      SysUser sysUser = userMapper.selectUserByLoginName(vehicleRepair.getCreateBy());
      if (sysUser != null) {
        vehicleRepair.setCreateUserName(sysUser.getUserName());
      }
      SysUser sysUser2 = userMapper.selectUserByLoginName(vehicleRepair.getApplyUser());
      if (sysUser2 != null) {
        vehicleRepair.setApplyUserName(sysUser2.getUserName());
      }
      // 当前环节
      if (StringUtils.isNotBlank(vehicleRepair.getInstanceId())) {
        List<Task> taskList = taskService.createTaskQuery()
          .processInstanceId(vehicleRepair.getInstanceId())
//                        .singleResult();
          .list();    // 例如请假会签，会同时拥有多个任务
        if (!CollectionUtils.isEmpty(taskList)) {
          TaskEntityImpl task = (TaskEntityImpl) taskList.get(0);
          vehicleRepair.setTaskId(task.getId());
          if (task.getSuspensionState() == 2) {
            vehicleRepair.setTaskName("已挂起");
            vehicleRepair.setSuspendState("2");
          } else {
            vehicleRepair.setTaskName(task.getName());
            vehicleRepair.setSuspendState("1");
          }
        } else {
          // 已办结或者已撤销
          vehicleRepair.setTaskName("已结束");
        }
      } else {
        vehicleRepair.setTaskName("未启动");
      }
      returnList.add(vehicleRepair);
    }
    returnList.setTotal(CollectionUtils.isEmpty(list) ? 0 : list.getTotal());
    returnList.setPageNum(pageNum);
    returnList.setPageSize(pageSize);
    return returnList;
  }

  /**
   * 新增维修申请
   *
   * @param bizVehicleRepair 维修申请
   * @return 结果
   */
  @Override
  public int insertBizVehicleRepair(BizVehicleRepair bizVehicleRepair) {
    bizVehicleRepair.setCreateBy(ShiroUtils.getLoginName());
    bizVehicleRepair.setCreateTime(DateUtils.getNowDate());
    return bizVehicleRepairMapper.insertBizVehicleRepair(bizVehicleRepair);
  }

  /**
   * 修改维修申请
   *
   * @param bizVehicleRepair 维修申请
   * @return 结果
   */
  @Override
  public int updateBizVehicleRepair(BizVehicleRepair bizVehicleRepair) {
    bizVehicleRepair.setUpdateTime(DateUtils.getNowDate());
    return bizVehicleRepairMapper.updateBizVehicleRepair(bizVehicleRepair);
  }

  /**
   * 删除维修申请对象
   *
   * @param ids 需要删除的数据ID
   * @return 结果
   */
  @Override
  public int deleteBizVehicleRepairByIds(String ids) {
    return bizVehicleRepairMapper.deleteBizVehicleRepairByIds(Convert.toStrArray(ids));
  }

  /**
   * 删除维修申请信息
   *
   * @param id 维修申请ID
   * @return 结果
   */
  @Override
  public int deleteBizVehicleRepairById(Long id) {
    return bizVehicleRepairMapper.deleteBizVehicleRepairById(id);
  }

  @Override
  public ProcessInstance submitApply(BizVehicleRepair bizVehicleRepair, String applyUserId, String key, HashMap<String, Object> variables) throws RuntimeException {
    bizVehicleRepair.setApplyUser(applyUserId);
    bizVehicleRepair.setApplyTime(DateUtils.getNowDate());
    bizVehicleRepair.setUpdateBy(applyUserId);
    bizVehicleRepairMapper.updateBizVehicleRepair(bizVehicleRepair);
    String businessKey = bizVehicleRepair.getId().toString(); // 实体类 ID，作为流程的业务 key

    ProcessInstance processInstance = processService.submitApply(applyUserId, businessKey, "repaire approve", bizVehicleRepair.getReason(), key, variables);

    String processInstanceId = processInstance.getId();
    bizVehicleRepair.setInstanceId(processInstanceId); // 建立双向关系
    bizVehicleRepairMapper.updateBizVehicleRepair(bizVehicleRepair);

    return processInstance;
  }



  /**
   * 查询已办列表
   */
  @Override
  public Page<BizVehicleRepairVo> findDoneTasks(BizVehicleRepairVo bizVehicleRepairVo, String userId) {
    // 手动分页
    PageDomain pageDomain = TableSupport.buildPageRequest();
    Integer pageNum = pageDomain.getPageNum();
    Integer pageSize = pageDomain.getPageSize();
    Page<BizVehicleRepairVo> list = new Page<>();

    List<BizVehicleRepairVo> results = new ArrayList<>();
    List<HistoricTaskInstance> hisList = processService.findDoneTasks(userId, "repair");
    // 根据流程的业务ID查询实体并关联
    for (HistoricTaskInstance instance : hisList) {
      String processInstanceId = instance.getProcessInstanceId();
      // 条件过滤 1
      if (StringUtils.isNotBlank(bizVehicleRepairVo.getInstanceId()) && !bizVehicleRepairVo.getInstanceId().equals(processInstanceId)) {
        continue;
      }
      HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
      String businessKey = processInstance.getBusinessKey();
      BizVehicleRepairVo bizVehicleRepairVo1 = bizVehicleRepairMapper.selectBizVehicleRepairById(new Long(businessKey));
      BizVehicleRepairVo newBizVehicleRepairVo = new BizVehicleRepairVo();
      BeanUtils.copyProperties(bizVehicleRepairVo1, newBizVehicleRepairVo);
      newBizVehicleRepairVo.setTaskId(instance.getId());
      newBizVehicleRepairVo.setTaskName(instance.getName());
      newBizVehicleRepairVo.setDoneTime(instance.getEndTime());
      SysUser sysUser = userMapper.selectUserByLoginName(bizVehicleRepairVo1.getApplyUser());
      newBizVehicleRepairVo.setApplyUserName(sysUser.getUserName());
      results.add(newBizVehicleRepairVo);
    }

    List<BizVehicleRepairVo> tempList;
    if (pageNum != null && pageSize != null) {
      int maxRow = (pageNum - 1) * pageSize + pageSize > results.size() ? results.size() : (pageNum - 1) * pageSize + pageSize;
      tempList = results.subList((pageNum - 1) * pageSize, maxRow);
      list.setTotal(results.size());
      list.setPageNum(pageNum);
      list.setPageSize(pageSize);
    } else {
      tempList = results;
    }

    list.addAll(tempList);
    return list;
  }

  @Override
  public Page<BizVehicleRepairVo> findTodoTasks(BizVehicleRepairVo bizVehicleRepairVo, String userId) {
    // 手动分页
    PageDomain pageDomain = TableSupport.buildPageRequest();
    Integer pageNum = pageDomain.getPageNum();
    Integer pageSize = pageDomain.getPageSize();
    Page<BizVehicleRepairVo> list = new Page<>();

    List<BizVehicleRepairVo> results = new ArrayList<>();
    List<Task> tasks = processService.findTodoTasks(userId, "repair");
    // 根据流程的业务ID查询实体并关联
    for (Task task : tasks) {
      TaskEntityImpl taskImpl = (TaskEntityImpl) task;
      String processInstanceId = taskImpl.getProcessInstanceId();
      // 条件过滤 1 流程实例一致性校验 如果不为空才需校验 默认为空
      if (StringUtils.isNotBlank(bizVehicleRepairVo.getInstanceId()) && !bizVehicleRepairVo.getInstanceId().equals(processInstanceId)) {
        continue;
      }
      ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
      String businessKey = processInstance.getBusinessKey();
      BizVehicleRepairVo bizVehicleRepairVo2 = bizVehicleRepairMapper.selectBizVehicleRepairById(new Long(businessKey));
      SysUser applyUser = userMapper.selectUserByLoginName(bizVehicleRepairVo2.getApplyUser());
      bizVehicleRepairVo2.setApplyUserName(applyUser.getUserName());
      bizVehicleRepairVo2.setTaskId(taskImpl.getId());
      if (taskImpl.getSuspensionState() == 2) {
        bizVehicleRepairVo2.setTaskName("已挂起");
      } else {
        bizVehicleRepairVo2.setTaskName(taskImpl.getName());
      }

      results.add(bizVehicleRepairVo2);
    }

    List<BizVehicleRepairVo> tempList;
    if (pageNum != null && pageSize != null) {
      int maxRow = (pageNum - 1) * pageSize + pageSize > results.size() ? results.size() : (pageNum - 1) * pageSize + pageSize;
      tempList = results.subList((pageNum - 1) * pageSize, maxRow);
      list.setTotal(results.size());
      list.setPageNum(pageNum);
      list.setPageSize(pageSize);
    } else {
      tempList = results;
    }

    list.addAll(tempList);

    return list;
  }

  @Override
  public Page<ExpenseReport> findTodoTasksMobile(ExpenseReport expenseReport, String loginName) {
    // 手动分页
    PageDomain pageDomain = TableSupport.buildPageRequest();
    Integer pageNum = pageDomain.getPageNum();
    Integer pageSize = pageDomain.getPageSize();
    Page<ExpenseReport> list = new Page<>();

    List<ExpenseReport> results = new ArrayList<>();
    List<Task> tasks = processService.findTodoTasks(loginName, "repair");
    // 根据流程的业务ID查询实体并关联
    for (Task task : tasks) {
      TaskEntityImpl taskImpl = (TaskEntityImpl) task;
      String processInstanceId = taskImpl.getProcessInstanceId();
      // 条件过滤 1 流程实例一致性校验 如果不为空才需校验 默认为空
      if (StringUtils.isNotBlank(expenseReport.getInstanceId()) && !expenseReport.getInstanceId().equals(processInstanceId)) {
        continue;
      }
      ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
      String businessKey = processInstance.getBusinessKey();

      StringBuilder sb = new StringBuilder();
      sb.append(dwUrl).append("/api/").append("expense").append("/detail/").append(businessKey);
      String s1 = HttpClientUtil.doGet(sb.toString());
      sb = null;

      if (StringUtils.isEmpty(s1) || s1.equalsIgnoreCase("-1")) {
        continue;
      }
      JSONObject jsonObject = JSON.parseObject(s1);
      JSONObject data = jsonObject.getJSONObject("data");
      ExpenseReport expenseReport2 = JSON.parseObject(data.toString(), ExpenseReport.class);
      String createrName = expenseReport2.getCreaterName();
      if (expenseReport2.getApplyUserName() == null) {
        SysUser applyUser = userMapper.selectUserByLoginName(createrName);
        if (applyUser != null)
          expenseReport2.setApplyUserName(applyUser.getUserName());
      }
      expenseReport2.setTaskId(taskImpl.getId());
      if (taskImpl.getSuspensionState() == 2) {
        expenseReport2.setTaskName("已挂起");
      } else {
        expenseReport2.setTaskName(taskImpl.getName());
      }
      StringBuilder sb1 = new StringBuilder();
      sb1.append(dwUrl).append("/api/").append("expense").append("/update/").append(expenseReport2.getId());
      JSONObject o = (JSONObject) JSONObject.toJSON(expenseReport2);
      String s = HttpClientUtil.doPost(sb1.toString(), o);
      if (StringUtils.isEmpty(s) || s.equalsIgnoreCase("-1")) {
        throw new RuntimeException("更新失败..");
      }
      results.add(expenseReport2);
    }

    List<ExpenseReport> tempList;
    if (pageNum != null && pageSize != null) {
      int maxRow = (pageNum - 1) * pageSize + pageSize > results.size() ? results.size() : (pageNum - 1) * pageSize + pageSize;
      tempList = results.subList((pageNum - 1) * pageSize, maxRow);
      list.setTotal(results.size());
      list.setPageNum(pageNum);
      list.setPageSize(pageSize);
    } else {
      tempList = results;
    }
    list.addAll(tempList);
    return list;
  }


}
